import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'

export function useLiveMixer() {
  // 全局变量
  const livePusher = ref(null)
  const videoEffectManager = ref(null)
  const streams = reactive(new Map())
  const selectedStreamId = ref(null)
  const streamCounter = ref(0)
  const canvasWidth = ref(1280)
  const canvasHeight = ref(720)
  const isPushing = ref(false)
  const scaleX = ref(1)
  const scaleY = ref(1)

  // 拉流相关
  const player = ref(null)
  const isPlaying = ref(false)
  const isPlayerInitializing = ref(false)

  // 拖拽相关
  const isDragging = ref(false)
  const isResizing = ref(false)
  const dragStartX = ref(0)
  const dragStartY = ref(0)
  const dragStreamId = ref(null)

  // 计算属性
  const streamCount = computed(() => streams.size)
  const canvasSize = computed(() => `${canvasWidth.value}x${canvasHeight.value}`)
  const avgScale = computed(() => ((scaleX.value + scaleY.value) / 2).toFixed(2))

  // MD5 加密函数（使用 Electron API）
  const md5 = (string) => {
    if (window.api && window.api.md5) {
      return window.api.md5(string)
    }
    throw new Error('MD5 API not available')
  }

  // 等待 SDK 加载
  const waitForSDK = (timeout = 15000) => {
    return new Promise((resolve, reject) => {
      const startTime = Date.now()
      
      const checkSDK = () => {
        const elapsed = Date.now() - startTime

        // 检查推流 SDK
        if (!window.TXLivePusher || typeof window.TXLivePusher !== 'function') {
          if (elapsed > timeout) {
            reject(new Error('TXLivePusher SDK 加载超时'))
            return
          }
          setTimeout(checkSDK, 100)
          return
        }

        // 检查播放器 SDK - 确保它是一个可调用的函数
        if (!window.TCPlayer || typeof window.TCPlayer !== 'function') {
          if (elapsed > timeout) {
            console.error('TCPlayer 状态:', {
              exists: !!window.TCPlayer,
              type: typeof window.TCPlayer,
              value: window.TCPlayer
            })
            reject(new Error('TCPlayer SDK 加载超时或不可用'))
            return
          }
          setTimeout(checkSDK, 100)
          return
        }

        console.log('✅ SDK 检测通过:', {
          TXLivePusher: typeof window.TXLivePusher,
          TCPlayer: typeof window.TCPlayer,
          耗时: elapsed + 'ms'
        })
        resolve(true)
      }

      // 延迟一点开始检测，给 SDK 一些初始化时间
      setTimeout(checkSDK, 500)
    })
  }

  // 初始化
  const init = async () => {
    try {
      // 等待 SDK 加载完成
      console.log('等待 SDK 加载...')
      await waitForSDK()
      console.log('✅ 所有 SDK 加载完成')

      if (!window.TXLivePusher) {
        console.error('TXLivePusher SDK 未加载')
        return false
      }

      livePusher.value = new window.TXLivePusher()
      livePusher.value.setRenderView('local_video')
      videoEffectManager.value = livePusher.value.getVideoEffectManager()
      
      // 启用本地混流
      videoEffectManager.value.enableMixing(true)
      
      // 设置初始混流配置
      updateMixingConfig()
      
      console.log('✅ LiveMixer 初始化完成')
      return true
    } catch (error) {
      console.error('❌ SDK 加载失败:', error.message)
      return false
    }
  }

  // 更新混流配置
  const updateMixingConfig = () => {
    if (!videoEffectManager.value) return

    videoEffectManager.value.setMixingConfig({
      videoWidth: canvasWidth.value,
      videoHeight: canvasHeight.value,
      videoFramerate: 15
    })
  }

  // 计算缩放比例
  const calculateScale = () => {
    const canvas = document.getElementById('preview-canvas')
    if (!canvas) return

    const rect = canvas.getBoundingClientRect()
    if (rect.width === 0 || rect.height === 0) {
      setTimeout(calculateScale, 100)
      return
    }

    scaleX.value = rect.width / canvasWidth.value
    scaleY.value = rect.height / canvasHeight.value

    console.log(`缩放比例: X=${scaleX.value.toFixed(3)}, Y=${scaleY.value.toFixed(3)}`)
  }

  // 应用布局
  const applyLayout = () => {
    if (streams.size === 0 || !videoEffectManager.value) return

    const layoutConfig = []

    streams.forEach((stream) => {
      let renderMode = 1 // 默认适应模式
      if (stream.fillMode === 'fit') {
        renderMode = 1
      } else if (stream.fillMode === 'fill') {
        renderMode = 0
      } else if (stream.fillMode === 'cover') {
        renderMode = 2
      }

      // SDK 使用中心点坐标
      const centerX = stream.x + stream.width / 2
      const centerY = stream.y + stream.height / 2

      const config = {
        streamId: stream.id,
        x: Math.round(centerX),
        y: Math.round(centerY),
        width: stream.width,
        height: stream.height,
        zOrder: stream.zOrder,
        renderMode: renderMode
      }
      layoutConfig.push(config)

      // 应用镜像
      if (stream.mirror) {
        videoEffectManager.value.setMirror({
          streamId: stream.id,
          mirrorType: 1
        })
      }
    })

    videoEffectManager.value.setLayout(layoutConfig)
    console.log('布局已更新:', layoutConfig)
  }

  // 生成推流地址
  const generatePushUrl = (domain, appName, streamName, key) => {
    if (!domain || !streamName || !key) {
      return ''
    }

    const txTime = (Math.floor(Date.now() / 1000) + 86400).toString(16).toUpperCase()
    const txSecret = md5(key + streamName + txTime)
    const path = `/${appName}/${streamName}`
    return `webrtc://${domain}${path}?txSecret=${txSecret}&txTime=${txTime}`
  }

  // 生成播放地址
  const generatePlayUrl = (domain, appName, streamName, protocol, key) => {
    if (!domain || !streamName) {
      return ''
    }

    const path = `/${appName}/${streamName}`
    let authParams = ''

    if (key) {
      const txTime = (Math.floor(Date.now() / 1000) + 86400).toString(16).toUpperCase()
      const txSecret = md5(key + streamName + txTime)
      authParams = `?txSecret=${txSecret}&txTime=${txTime}`
    }

    let playUrl = ''
    switch (protocol) {
      case 'webrtc':
        playUrl = `webrtc://${domain}${path}${authParams}`
        break
      case 'flv':
        playUrl = `http://${domain}${path}.flv${authParams}`
        break
      case 'hls':
        playUrl = `http://${domain}${path}.m3u8${authParams}`
        break
      default:
        return ''
    }

    return playUrl
  }

  // 添加摄像头
  const addCamera = async (config) => {
    if (!livePusher.value) return null

    const streamId = await livePusher.value.startCamera()
    await livePusher.value.startMicrophone()

    streamCounter.value++

    const stream = {
      id: streamId,
      name: config.name || `摄像头-${streamCounter.value}`,
      type: 'camera',
      x: config.x || 50,
      y: config.y || 50,
      width: config.width || 320,
      height: config.height || 180,
      zOrder: streamCounter.value,
      mirror: false,
      fillMode: config.fillMode || 'fit'
    }

    streams.set(streamId, stream)
    applyLayout()

    return stream
  }

  // 添加屏幕分享
  const addScreen = async (config, sourceId) => {
    if (!livePusher.value) return null

    let streamId
    let mediaStream = null

    // Electron 环境特殊处理
    if (sourceId) {
      const constraints = {
        audio: false,
        video: {
          mandatory: {
            chromeMediaSource: 'desktop',
            chromeMediaSourceId: sourceId
          }
        }
      }

      mediaStream = await navigator.mediaDevices.getUserMedia(constraints)
      const videoTrack = mediaStream.getVideoTracks()[0]

      if (typeof livePusher.value.startCustomCapture === 'function') {
        streamId = await livePusher.value.startCustomCapture(mediaStream)
      } else {
        streamId = 'screen_' + Date.now()
        if (!window.customScreenStreams) {
          window.customScreenStreams = new Map()
        }
        window.customScreenStreams.set(streamId, mediaStream)
      }
    } else {
      streamId = await livePusher.value.startScreenCapture()
    }

    streamCounter.value++

    const stream = {
      id: streamId,
      name: config.name || `屏幕分享-${streamCounter.value}`,
      type: 'screen',
      x: config.x || 0,
      y: config.y || 0,
      width: config.width || canvasWidth.value,
      height: config.height || canvasHeight.value,
      zOrder: streamCounter.value,
      mirror: false,
      fillMode: config.fillMode || 'fit',
      mediaStream: mediaStream
    }

    streams.set(streamId, stream)
    applyLayout()

    return stream
  }

  // 移除流
  const removeStream = (streamId) => {
    const stream = streams.get(streamId)
    if (!stream) return

    try {
      if (stream.type === 'camera') {
        livePusher.value.stopCamera(streamId)
        livePusher.value.stopMicrophone(streamId)
      } else if (stream.type === 'screen') {
        try {
          livePusher.value.stopCustomCapture(streamId)
        } catch (e) {
          if (stream.mediaStream) {
            stream.mediaStream.getTracks().forEach(track => track.stop())
          }
        }
      }
    } catch (error) {
      console.warn('停止流时出错:', error)
    }

    streams.delete(streamId)
    
    if (selectedStreamId.value === streamId) {
      selectedStreamId.value = null
    }

    if (streams.size > 0) {
      applyLayout()
    } else {
      videoEffectManager.value?.setLayout([])
    }
  }

  // 更新流属性
  const updateStream = (streamId, updates) => {
    const stream = streams.get(streamId)
    if (!stream) return

    Object.assign(stream, updates)
    applyLayout()
  }

  // 开始推流
  const startPush = async (pushUrl) => {
    if (!livePusher.value || !pushUrl) return false

    try {
      await livePusher.value.startPush(pushUrl)
      isPushing.value = true
      console.log('推流已启动')
      return true
    } catch (error) {
      console.error('推流失败:', error)
      isPushing.value = false
      return false
    }
  }

  // 停止推流
  const stopPush = () => {
    if (!livePusher.value) return

    livePusher.value.stopPush()
    isPushing.value = false
    console.log('推流已停止')
  }

  // 开始播放
  const startPlay = async (playUrl) => {
    if (isPlayerInitializing.value) return false

    // 检查 TCPlayer 是否加载
    if (!window.TCPlayer || typeof window.TCPlayer !== 'function') {
      console.error('TCPlayer SDK 未加载')
      alert('播放器 SDK 未加载完成，请稍后重试或刷新页面')
      return false
    }

    isPlayerInitializing.value = true

    try {
      // 销毁旧播放器
      if (player.value) {
        try {
          player.value.dispose()
          player.value.destroy()
        } catch (e) {
          console.warn('销毁播放器失败:', e)
        }
        player.value = null
      }

      // 创建新播放器
      player.value = window.TCPlayer('player-video', {
        sources: [{ src: playUrl }],
        autoplay: true,
        preload: 'auto',
        width: '100%',
        height: '100%',
        playsinline: true,
        controls: true,
        webrtcConfig: {
          connectRetryCount: 3,
          connectRetryDelay: 1000
        }
      })

      // 监听事件
      player.value.on('playing', () => {
        isPlaying.value = true
        isPlayerInitializing.value = false
        console.log('播放成功')
      })

      player.value.on('error', (error) => {
        console.error('播放错误:', error)
        isPlayerInitializing.value = false
      })

      return true
    } catch (error) {
      console.error('创建播放器失败:', error)
      isPlayerInitializing.value = false
      return false
    }
  }

  // 停止播放
  const stopPlay = () => {
    isPlayerInitializing.value = false

    if (player.value) {
      try {
        player.value.dispose()
        player.value.destroy()
      } catch (e) {
        console.warn('销毁播放器失败:', e)
      }
      player.value = null
    }

    isPlaying.value = false
    console.log('播放已停止')
  }

  return {
    // 状态
    livePusher,
    videoEffectManager,
    streams,
    selectedStreamId,
    streamCounter,
    canvasWidth,
    canvasHeight,
    isPushing,
    scaleX,
    scaleY,
    player,
    isPlaying,
    isPlayerInitializing,
    isDragging,
    isResizing,
    dragStartX,
    dragStartY,
    dragStreamId,

    // 计算属性
    streamCount,
    canvasSize,
    avgScale,

    // 方法
    init,
    updateMixingConfig,
    calculateScale,
    applyLayout,
    generatePushUrl,
    generatePlayUrl,
    addCamera,
    addScreen,
    removeStream,
    updateStream,
    startPush,
    stopPush,
    startPlay,
    stopPlay,
    md5
  }
}

